import {getMd5} from "./index.js"
let env = process.env.NODE_ENV === 'development'
const BASE_URL = env ? 'https://hlwyy-api-test.yhfhyy.com.cn/app' : 'https://hlwyy-api.yhfhyy.com.cn/app';
const timeout = 15000
let netCount = 0
const salt="myk44GYlfLIjvUBnuhZk7kFfOurX6f"
//默认参数
let defaultParams = {
	channel: "1",
	format: "JSON",
	hosId: "1300000000",
	oper: "127.0.0.1",
	packageName: "com.tybzyy.fenhuangpat",
	random: parseInt(Math.random()*1000+10000)+"",
	source: "BJYH",
	spid: "459387049244558",
	ts: Date.now()+"",
	version: "24",
	bookType: "0"
}

async function request(data, method) {
	if (netCount === 0) {
		uni.showLoading({
			title: '加载中...'
		});
	}
	netCount++
	// 发起网络请求

	let res, err;
	try {
		let req = getMd5(defaultParams, data || {}, salt)
		console.log("请求参数==>",req)
		req.obj.sign=req.sign
		res = await uni.request({
			url: BASE_URL,
			data: req.obj,
			method: method || "GET",
			timeout,
			noncestr: Date.now(),
			header: {
				'content-type': 'application/json',
				'token': uni.getStorageSync('token') || '',
				'sign': req.sign,
				'spid': defaultParams.spid,
				'ts': defaultParams.ts
			}
		});
		console.log("响应参数==>",res)
	} catch (e) {
		err = e
	} finally {
		netCount--
		if (netCount === 0) {
			// 关闭加载
			debounce(() => uni.hideLoading());
		}
	}

	if (err) {
		console.log('request fail', err);
		uni.showModal({
			content: err.errMsg,
			showCancel: false
		});
	} else {
		//登录过期,直接去登录页面
		if (res.statusCode === 200 && res.data.code === 5555) {
			uni.showToast({
				title: res.data.msg,
				duration: 1500,
			});
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/login'
				})
			}, 1500)
			return
		} else if (res.statusCode === 200 && res.data.code === "0") {
			return res.data
		} else if (res.statusCode === 200 && ([-1, -4, '-1', '-4'].includes(res.data.code))) {
			uni.showToast({
				title: res.data.msg,
				icon: 'none',
				duration: 1500,
			});
			// uni.removeStorageSync("token")
			return res.data
		} else {
			// 响应失败，给用户提示
			uni.showToast({
				title: res.data.msg,
				icon: 'none',
				mask: true,
				duration: 1500,
			});
		}

	}
}


let timer;

function debounce(fn, wait = 500) {
	if (timer) {
		clearTimeout(timer);
	}
	timer = setTimeout(fn, wait);
}

// export default {
// 	get: (url, data) => request(url, data),
// 	post: (url, data) => request(url, data, "POST")
// };

export default {
	get: (data) => request(data),
	post: (data) => request(data, "POST")
};